import { env } from "@/lib/env";
import { getServerAuthCookies } from "@/lib/server-auth";
import type { OutputsPaginated, ProjectDetail, ProjectSummary } from "@/lib/types";

import type { LoginResponse } from "./api-client";

const EMPTY_OUTPUTS: OutputsPaginated = {
  items: [],
  meta: {
    total: 0,
    page: 1,
    pageSize: 0,
    pageCount: 0,
  },
};

export async function getAuthenticatedUser() {
  const { accessToken } = getServerAuthCookies();

  if (!accessToken) {
    return null;
  }

  const response = await fetch(new URL("/auth/me", env.apiBaseUrl).toString(), {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
    cache: "no-store",
  });

  if (!response.ok) {
    return null;
  }

  const json = (await response.json()) as LoginResponse["user"];
  return json;
}

export async function getProjectSummaries(): Promise<ProjectSummary[]> {
  const { accessToken } = getServerAuthCookies();

  if (!accessToken) {
    return [];
  }

  const response = await fetch(new URL("/projects", env.apiBaseUrl).toString(), {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
    cache: "no-store",
  });

  if (!response.ok) {
    return [];
  }

  const json = (await response.json()) as ProjectSummary[];
  return json;
}

export async function getProjectDetail(id: string): Promise<ProjectDetail | null> {
  const { accessToken } = getServerAuthCookies();

  if (!accessToken) {
    return null;
  }

  const response = await fetch(new URL(`/projects/${id}`, env.apiBaseUrl).toString(), {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
    cache: "no-store",
  });

  if (!response.ok) {
    if (response.status === 404) {
      return null;
    }
    throw new Error("Failed to load project detail");
  }

  const json = (await response.json()) as ProjectDetail;
  return json;
}

export interface GetDailyOutputsParams {
  from?: string;
  to?: string;
  projectId?: string;
  page?: number;
  pageSize?: number;
}

export async function getDailyOutputs(params: GetDailyOutputsParams = {}): Promise<OutputsPaginated> {
  const { accessToken } = getServerAuthCookies();

  if (!accessToken) {
    return EMPTY_OUTPUTS;
  }

  const today = new Date().toISOString().slice(0, 10);
  const from = params.from ?? today;
  const to = params.to ?? params.from ?? today;
  const page = params.page ?? 1;
  const pageSize = params.pageSize ?? 50;

  const url = new URL("/outputs", env.apiBaseUrl);
  const search = new URLSearchParams({
    from,
    to,
    page: String(page),
    pageSize: String(pageSize),
  });

  if (params.projectId) {
    search.set("projectId", params.projectId);
  }

  url.search = search.toString();

  const response = await fetch(url.toString(), {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
    cache: "no-store",
  });

  if (!response.ok) {
    if (response.status === 404 || response.status === 204) {
      return EMPTY_OUTPUTS;
    }

    if (response.status === 401) {
      return EMPTY_OUTPUTS;
    }

    throw new Error("Failed to load outputs");
  }

  const json = (await response.json()) as OutputsPaginated;
  return json;
}
